import 'dart:ui';

import 'package:desktop_drop/desktop_drop.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:starkylin_file_shared/starkylin_file_shared.dart';
import 'package:starkylin_file_shared/type/type.dart';
import 'package:starkylin_file_shared_example/indexed.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool dragging = false;
  final _starkylinFileSharedPlugin = StarkylinFileShared();
  MsgPack? msgPack;
  String selectFileText = "选择文件";
  String selectDirText = "选择文件夹";

  @override
  void initState() {
    super.initState();
    initPlatformState();
    _starkylinFileSharedPlugin.addMessageListener((pack) {
      print("pack: ${pack.pathList}");
      setState(() {
        msgPack = pack;
      });
    });
  }

  Cancel? token;
  Widget getTextButton() {
    if (msgPack == null) {
      return Container();
    } else {
      return TextButton(
          onPressed: () async {
            if (token == null) {
              token = await _starkylinFileSharedPlugin.download(msgPack!);
            } else {
              token!.cancel();
              token = null;
            }
            setState(() {});
          },
          child: Text(token == null ? '下载文件' : '取消下载'));
    }
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      // platformVersion = await _starkylinFileSharedPlugin.getPlatformVersion() ??
      //     'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      // _platformVersion = platformVersion;
    });
  }

  // 改变拖拽状态
  void changeDragState(bool status) {
    print("changeDragState: ");
    setState(() {
      dragging = status;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Plugin example app'),
          ),
          body: DropTarget(
              enable: true,
              onDragDone: (detail) {
                for (var item in detail.files) {
                  print("object: ${item.path}");
                  print("onDragDone: ${item.path}");
                }
                changeDragState(false);
              },
              onDragEntered: (details) => changeDragState(true),
              onDragExited: (details) => changeDragState(false),
              // onDragUpdated: (details) => setState(() {}),
              child: Indexer(
                children: [
                  Indexed.fromWidget(
                      Positioned(
                        top: 40,
                        left: 100,
                        child: MouseRegion(
                          child: TextButton(
                            onPressed: () async {
                              var ret =
                                  await _starkylinFileSharedPlugin.selectDir();
                              print('ret $ret');
                              if (ret != null) {
                                await _starkylinFileSharedPlugin
                                    .sendDirFromPath(ret);
                              }
                            },
                            child: Text(selectDirText),
                          ),
                        ),
                      ),
                      0),
                  Indexed.fromWidget(
                      Positioned(
                        child: MouseRegion(
                          onEnter: (event) => setState(() {
                            selectFileText = "选择文件选择文件选择文件";
                          }),
                          onExit: (event) => setState(() {
                            selectFileText = "选择文件";
                          }),
                          onHover: (event) => print('onHover'),
                          child: TextButton(
                            child: Text(selectFileText),
                            onPressed: () async {
                              var ret =
                                  await _starkylinFileSharedPlugin.selectFile();
                              await _starkylinFileSharedPlugin
                                  .sendFileFromPath(ret);
                            },
                          ),
                        ),
                      ),
                      1),
                  Indexed.fromWidget(getTextButton(), 2),
                  if (dragging)
                    Indexed.fromWidget(Center(
                      child: LayoutBuilder(
                        builder: (context, constrait) {
                          var width = constrait.maxWidth;
                          var height = constrait.maxHeight;
                          return Container(
                              // color: Colors.red.withAlpha(92),
                              width: width * 0.9,
                              height: height,
                              child: BackdropFilter(
                                filter: ImageFilter.blur(sigmaX: 4, sigmaY: 4),
                                child: const Center(
                                  child: Text(
                                    '释放以分享文件到共享窗口~',
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20,
                                    ),
                                  ),
                                ),
                              ));
                        },
                      ),
                    ), 0),
                ],
              ))),
    );
  }
}
